<template>
	<view class="content">
		<!-- 返现配置 -->
		<view class="redemptionSettingsCode">
			<view style="font-weight: 700; font-size: 30rpx;margin-bottom: 10rpx;">
				返现配置
			</view>

			<uni-forms :modelValue="form" :rules="rules" label-position="top">

				<uni-forms-item label="现金返现" required labelWidth="180px">
					<uni-data-checkbox @change="cashCashbackFn" v-model="form.returnCashType"
						:localdata="cashback"></uni-data-checkbox>

				</uni-forms-item>

				<view v-if="form.returnCashType==1">
					<uni-forms-item label="返现金额" required labelWidth="180px">
						<uni-easyinput type='number' v-model="form.returnCashAmount" placeholder="请输入返现金额(元)" />

					</uni-forms-item>
				</view>
				<view v-if="form.returnCashType==2">
					<uni-forms-item label="返现比例" labelWidth="180px">
						<zjy-easyinput v-model="form.returnCashRatio" placeholder="请输入返现比例(%)" type='number'
							maxlength='3'></zjy-easyinput>
						<!-- <zjy-easyinput v-model="form.returnCashRatio" type='number' placeholder="请输入内容" maxlength='2'
							placeholder="请输入返现比例" :buttonInfo="buttonInfo1"/>
 -->
					</uni-forms-item>
				</view>
				<!-- 	<uni-forms-item label="返现时间" name="returnCashTime" required labelWidth="180px">
					<uni-easyinput v-model="form.returnCashTime" placeholder="请选择返现时间" />

				</uni-forms-item> -->
				<view style="font-weight: 700; font-size: 30rpx;margin-bottom: 10rpx;">
					选择素材
				</view>
				<uni-data-checkbox v-model="form.materialType" :localdata="sourceMaterial"></uni-data-checkbox>


				<uni-forms-item label="文件夹" required name="videoMaterialId">
					<view class="selectProject">
						<e-select placeholder='请选择文件夹' v-model="form.videoMaterialId" :options="options1"
							@change="change1">
							<!-- 内置插槽，可以搭配官方uni-ui的分页组件使用 -->
							<uni-pagination show-icon="true" :total="total" :pageSize="5" :current="1"
								@change="page1"></uni-pagination>
						</e-select>
					</view>
				</uni-forms-item>
				<uni-forms-item label="SEO文案" required name="seoCopywritingId">
					<view class="selectProject">
						<e-select placeholder='请选择SEO文案' v-model="form.seoCopywritingId" :options="options2"
							@change="change2">
							<!-- 内置插槽，可以搭配官方uni-ui的分页组件使用 -->
							<uni-pagination show-icon="true" :total="totalSeo" :pageSize="5" :current="1"
								@change="page2"></uni-pagination>
						</e-select>
					</view>
				</uni-forms-item>
				<view style="font-weight: 700; font-size: 30rpx;margin-bottom: 10rpx;">
					渠道与挂载
				</view>

				<view style="font-weight: 700; font-size: 30rpx;margin-bottom: 10rpx;">
					<uni-forms-item label="发布设置" required>
						<view>
							<uni-data-checkbox v-model="form.shareToPublish" :localdata="publishSetting" />
						</view>
					</uni-forms-item>

					<uni-forms-item label="挂载类型" required>
						<view>
							<uni-data-checkbox v-model="form.mountType" :localdata="mountTypeList"
								@change="getMountType" />
						</view>
					</uni-forms-item>
					<!-- 选择城市 -->
					<view v-if="mountTypeSwitch==1">
						<uni-forms-item style="flex-direction: row; align-items: baseline;" label="选择城市" required
							name="cityName">

							<view class="selectCity" @click="handleRegion()">
								<uni-easyinput disabled v-model="form.cityName" placeholder="请选择城市" />

								<uni-icons class="dropDownImage" color="#999" type="bottom" size="14"></uni-icons>
							</view>
						</uni-forms-item>
						<!-- 商家简称 -->



						<uni-forms-item label="商家简称" required name="keyword"
							style="flex-direction: row;align-items: baseline;" label-align=" 140rpx">
							<view class=" searchButton">
								<uni-easyinput v-model="form.merchantAbbreviation" placeholder="请输入商家简称搜索POI" />
								<view class="searchText" @click="searchPOI">
									搜索
								</view>
							</view>
						</uni-forms-item>


						<uni-forms-item label="Poi地址" required name="seoCopywritingId"
							style="flex-direction: row;align-items: baseline;">
							<view class="selectProject">
								<e-select placeholder='请选择Poi地址' v-model="form.poiId" :options="options3"
									@change="change3">
									<!-- 内置插槽，可以搭配官方uni-ui的分页组件使用 -->
									<uni-pagination show-icon="true" :total="totalPoi" :pageSize="totalPoi" :current="1"
										@change="page3"></uni-pagination>
								</e-select>
							</view>
						</uni-forms-item>


						<!-- <picker mode="selector" @change='getPoiAddress' :range-key="'text'">
							<uni-forms-item style="flex-direction: row;align-items: baseline;" label="Poi地址" required
								name="poiName">
								<view class="selectProject">
									<uni-easyinput disabled type="text" v-model="form.poiName" placeholder="请输入Poi地址" />
									<uni-icons class="dropDownicons" color="#999" type="bottom" size="14">
									</uni-icons>
								</view>
							</uni-forms-item>
						</picker> -->
					</view>
					<view v-if="mountTypeSwitch==2">
						<!-- D音小程序APPID -->
						<uni-forms-item label="小程序APPID" required name="xcxId"
							style="flex-direction: row;    align-items: baseline;" label-align="200rpx">
							<uni-easyinput v-model="form.xcxId " placeholder="请输入D音小程序APPID" />
						</uni-forms-item>
						<uni-forms-item label="D音小程序名称" required name="xcxTitle"
							style="flex-direction: row;    align-items: baseline;" label-align="140rpx">
							<uni-easyinput v-model="form.xcxTitle" placeholder="请输入D音小程序名称" />
						</uni-forms-item>
						<!-- 选择poi地址 -->
						<uni-forms-item label="D音小程序URL" required name="xcxAddress"
							style="flex-direction: row;align-items: baseline;">
							<uni-easyinput v-model="form.xcxAddress " placeholder="请输入D音小程序URL" />
						</uni-forms-item>
					</view>

				</view>
			</uni-forms>
			<view class="sumbit-btn flex" @click.stop="saveInfo('form')">
				保存信息
			</view>


		</view>

		<lb-picker ref="picker2" v-model="value2" mode="multiSelector" confirmColor="#6568F6" :list="regionList"
			:props="factoryProp" :level="2" @confirm="handleConfirm" @cancel="handleCancel">
			<template>
				<view slot="action-center">选择城市</view>
			</template>
		</lb-picker>
	</view>
</template>

<script>
	// 获取城市
	import ZjyEasyinput from '@/uni_modules/zjy-easyinput/components/zjy-easyinput/zjy-easyinput.vue'

	import lbPicker from '@/components/lb-picker/index.vue'
	import regionList from '@/utils/positionPicker.js';
	import {
		object2Url
	} from '@/utils/trans';
	export default {
		components: {
			lbPicker,
			ZjyEasyinput
		},
		data() {
			return {
				buttonInfo1: {
					title: '查询',
					type: 'primary',
					size: 'mini',
				},
				page: 1,
				pageSeo: 1,
				value: '',
				value2: [],
				options1: [],
				total: '',
				factoryProp: {
					label: 'name',
					value: 'id'
				},
				regionList: regionList.zones_tree,
				mountTypeSwitch: 1,
				cashback: [{
					text: '固定金额',
					value: 1
				}, {
					text: '付款比例',
					value: 2
				}],
				sourceMaterial: [{
					text: '云创作成片库',
					value: 1
				}, {
					text: '云闪推成片库',
					value: 2
				}],
				title: 'paymentConfiguration',
				publishSetting: [{
					text: '跳转到发布页',
					value: 1,

				}, {
					text: '跳转到剪辑页',
					value: 0,

				}, ],
				mountTypeList: [{
					text: '商家POI',
					value: 1,

				}, {
					text: '小程序',
					value: 2,

				}, {
					text: '不挂载',
					value: 3,

				}, ],
				form: {

					// 返现时间
					returnCashTime: 24,
					//  返现比例
					returnCashRatio: '',
					//   返现金额
					returnCashAmount: '',
					// 返回类型
					returnCashType: 1,
					//   authorizedNot: 1, // 是否默认授权发布  1.否 2.是
					//   douPayNot: 2, // 抖支付开启：2，默认不开启：1，开启
					merchantId: JSON.parse(uni.getStorageSync('merchantId')), // 商户id

					//   id: this.$store.state.user.info.merchantId,
					//   activityType: 1,
					//   // 云创作成片库/云闪推成片库，分类
					materialType: 1,
					videoMaterialId: '',
					videoMaterial: null, //剪辑工程名
					seoCopywritingId: '', //SEO ID
					seoCopywriting: '', //SEO名称

					//   // 发布渠道
					// releaseChannel: 1,
					//   // 挂载类型
					mountType: 1,

					shareToPublish: 1, //发布设置 必填
					//   小程序链接
					xcxAddress: null,
					//   小程序标题
					xcxTitle: null,
					//   小程序地址
					xcxId: null,
					// 商家简称
					merchantAbbreviation: '',
					// 城市
					city: '',
					// 城市名字
					cityName: '',
					poiName: '',
					poiId: '',
					id: ''
				},
				options2: [],
				options3: [],
				totalSeo: '',
				dataArr: {
					list: [],
					total: 0
				},
				totalPoiAddres: '',
				load: false,
				cloudCreationFileList: [],
				totalPoi: '',
				// 关键词

				merchantId: JSON.parse(uni.getStorageSync('merchantId')),
				isUpdata: false,
				rules: {
					// 活动名称
					videoMaterialId: {
						rules: [{
							required: true,
							errorMessage: '文件夹不能为空'
						}]
					},
					// 活动说明
					seoCopywritingId: {
						rules: [{
							required: true,
							errorMessage: 'seo文案不能为空'
						}]
					},


				},

			}
		},
		mounted() {
			this.httpRequests()
			this.cloudCreationSeo()
			this.query()


			console.log(JSON.parse(uni.getStorageSync('merchantId')))

		},
		methods: {
			async query() {
				const reuslt = await this.$http.post({
					url: this.$api.getActivityconfigList,
					data: {

						limit: 10,
						merchantId: this.merchantId,
						page: 1,

					}
				})

				if (reuslt.code == 2000 && reuslt.data.list.length) {

					console.log(reuslt.data)
					this.$sun.assignObject(this.form, {
						...reuslt.data.list[0]
					})
					this.form.returnCashType = Number(reuslt.data.list[0].returnCashType)
					// this.form.seoCopywritingId=Number(reuslt.data.list[0].returnCashType)
					// this.form.videoMaterialId=Number(reuslt.data.list[0].videoMaterialId)
					this.mountTypeSwitch = reuslt.data.list[0].mountType
					console.log(this.form + '===================')
					this.isUpdata = true;
					this.searchApi()
				} else {
					this.isUpdata = false;
				}

			},
			change1(item) {
				console.log(item.text);
				console.log(item.value);

				this.form.videoMaterial = item.text
				this.form.videoMaterialId = item.value
			},
			change3(item) {
				console.log(item.text);
				console.log(item.value);
				this.form.poiName = item.text
				this.form.poiId = item.value
			},
			change2(item) {
				console.log(item.text);
				console.log(item.value);
				this.form.seoCopywritingId = item.value
				this.form.seoCopywriting = item.text
			},
			page1(item) {


				console.log(item);
				if (item.type == 'next') {
					this.page = item.current
					this.httpRequests()
				} else if (item.type == 'prev') {
					this.page = item.current
					this.httpRequests()
				}
			},
			page2() {
				console.log(item);
				if (item.type == 'next') {
					this.page = item.current
					this.cloudCreationSeo()
				} else if (item.type == 'prev') {
					this.page = item.current
					this.cloudCreationSeo()
				}
			},


			cashCashbackFn(e) {
				console.log(e.detail.value)
				if (e.detail.value == 1) {
					this.form.returnCashType = Number(e.detail.value);
					// 是否为固定金额
					this.form.returnCashRatio = ''
				} else {
					this.form.returnCashType = Number(e.detail.value);
					this.form.returnCashAmount = ''
				}
			},
			async searchPOI() {

				if (!this.form.cityName) {
					this.$sun.toast('请选择城市')
					return
				}
				if (!this.form.merchantAbbreviation) {
					this.$sun.toast('请输入商家简称')

					return
				}

				this.searchApi()





				// if (res.code = 2000) {
				// 	let poi_nameArr = res.data.map((item, index) => {
				// 		return {
				// 			text: item.poi_name,
				// 			value: item.poi_id,
				// 		}
				// 	})
				// 	const indexFind = poi_nameArr.findIndex((item) => {
				// 		return item.value == this.typeFormData.poi_id
				// 	})
				// 	if (indexFind !== -1) {

				// 		// 还有显示
				// 		this.typeFormData.poi_name = poi_nameArr[indexFind].text
				// 		// this.typeFormData.poi_name=poi_nameArr[]
				// 	}

				// 	this.allSearchPoiAddress = poi_nameArr
				// 	console.log(this.allSearchPoiAddress)
				// },

			},
			async searchApi() {
				const ts = new Date().getTime();
				const ua = navigator.userAgent;
				const us = {
					ua,
					ts,
					cursor: 0,
					keyword: this.form.merchantAbbreviation,
					city: this.form.city,
					count: 20,
					merchantId: this.merchantId
				};

				const res = await this.$http.get({
					url: this.$api.dyPoi + `${object2Url(us)}`,
					data: {
						...us
					},
				});
				// this.totalPoiAddres = (res.data.data.pois.length) - 1

				console.log(res)
				if (res.code == 2000) {
					const poiIdName = res.data.data.pois.map((item) => {
						return {
							text: item.poi_name,
							value: item.poi_id
						}
					})
					if (!(this.form.poiId || this.form.poiName)) {
						this.form.poiId = poiIdName[0].value
						this.form.poiName = poiIdName[0].text
					}
					this.totalPoi = poiIdName.length - 1


					this.options3 = poiIdName
				} else {
					console.log(res)
					this.$sun.toast(res.msg)
				}
			},
			handleConfirm(e) {
				let index = e.index;
				console.log(e)
				let firstIndex = index[0];
				let secondIndex = index[1];
				// let thridIndex = index[2];

				let firstStatus = this.regionList[firstIndex].name;
				let secondStatus = this.regionList[firstIndex].children[secondIndex].name;
				let city = this.regionList[firstIndex].children[secondIndex].code
				// let thridStatus = this.regionList[firstIndex].children[secondIndex].children[thridIndex];
				// 获取到城市位置
				console.log(this.regionList)
				console.log(`${firstStatus+'-'+secondStatus}`, city)
				// const pio_address=`${firstStatus+'-'+secondStatus}`
				this.$set(this.form, 'cityName', `${firstStatus+'-'+secondStatus}`);
				this.$set(this.form, 'city', city);
			},
			async httpRequests() {

				const res = await this.$http.post({
					url: this.$api.cloudCreationFile,
					data: {
						limit: 5,
						max: 1,
						page: this.page,
						username: uni.getStorageSync('staffCode')
					},
				});
				console.log(JSON.stringify(res) + '==================================文件夹')
				if (res.code == 2000) {
					this.total = res.data.count
					const result = res.data.list.map((item) => {
						return {
							text: item.name,
							value: item.id
						}
					})

					this.options1 = result


				}

			},
			async cloudCreationSeo() {
				const res = await this.$http.post({
					url: this.$api.cloudCreationSeo,
					data: {
						limit: 5,
						page: this.pageSeo,
						platform: 1,
						username: uni.getStorageSync('staffCode')
					},
				});
				console.log(res)
				if (res.code == 2000) {
					this.totalSeo = res.data.count
					const result = res.data.list.map((item) => {
						return {
							text: item.taticsName,
							value: item.id
						}
					})

					this.options2 = result


				}
			},
			getMountType(e) {
				console.log(e.detail.data.value);
				uni.showLoading({
					title: '加载中',

				});
				setTimeout(() => {
					uni.hideLoading();
					this.mountTypeSwitch = e.detail.data.value
					this.clear()
				}, 0);
				// this.mountTypeSwitch = 2

			},
			clear() {
				if (this.form.mountType == 2) {
					this.form.merchantAbbreviation = ''
					this.form.poiName = ''
					this.form.poiId = ''
					this.form.cityName = ''
					this.form.city = '',
						this.options3 = []

				}
				if (this.form.mountType == 1) {
					this.form.xcxAddress = ''
					this.form.xcxTitle = ''
					this.form.xcxId = ''
				}
				if (this.form.mountType == 3) {
					this.form.merchantAbbreviation = ''
					this.form.poiName = ''
					this.form.cityName = ''
					this.form.city = ''


					this.form.xcxAddress = ''
					this.form.xcxTitle = ''
					this.form.xcxId = ''
				}
				console.log("this.form", this.form)
			},
			handleRegion() {
				this.$refs['picker2'].show();
			},
			// 保存信息

			saveInfo(formName) {
				console.log(this.form, this.isUpdata)
				if (this.form.mountType == 2) {
					if (!(this.form.xcxAddress && this.form.xcxId && this.form.xcxTitle)) {

						this.$sun.toast('请填写小程序必要参数', '')
						return
					}
				}

				if (!(this.form.returnCashRatio || this.form.returnCashAmount)) {
					this.$sun.toast('请输入返现比例或者返现金额', '')

					return
				}

				if (!(this.form.videoMaterial && this.form.videoMaterialId)) {

					this.$sun.toast('请选择文件素材', '')
					return
				}

				if (this.form.mountType == 1) {
					console.log(this.form.poiName, this.form.merchantAbbreviation, this.form.cityName)
					if (!(this.form.poiName && this.form.merchantAbbreviation && this.form.cityName)) {
						console.log('请填写poi地址的必要参数', '')
						this.$sun.toast('请填写poi地址的必要参数', '')

						return
					}
				}
				if (!this.form.seoCopywriting) {
					this.$sun.toast('请选择seo文案', '')

					return
				}

				this.issues()

			},
			async issues() {
				// if(this.form.activityType!=4){
				//   delete this.form.cardsettings
				// }
				this.$at.uniDoFunc({
					key: 'release',
					success: async () => {
						this.$at.lockKey('release');
						if (this.isUpdata) {
							delete this.form.merchantId
						}
						console.log("this.form", this.form)
						const saveOrUpdate = this.isUpdata ? this.$api.updateActivityconfig : this.$api
							.addActivityconfig;


						if (this.isUpdata) {
							delete this.form.merchantId
						}
						this.form.returnCashTime = 24
						console.log(saveOrUpdate)
						const res = await this.$http.post({
							url: saveOrUpdate,
							data: {
								...this.form
							},
						});
						console.log(res)
						if (res.code == 2000) {

							this.query()
							setTimeout(() => {
								this.$sun.toast(res.msg)
							}, 200)
							this.$at.releaseKey('release');
						} else {

							this.query()
							setTimeout(() => {
								this.$sun.toast(res.msg)
							}, 200)
							this.$at.releaseKey('release');
						}

					}
				});

			},


		}
	}
</script>

<style lang="less">
	/deep/ e-select {
		text-align: left;
	}

	page {
		background-color: #f9f9f9;
	}

	.content {
		padding: 20rpx 30rpx;

		.redemptionSettingsCode {
			background-color: #fff;
			padding: 20rpx;
		}



		.sumbit-btn {
			width: 670rpx;

			height: 100rpx;
			color: #fff;
			border-radius: 10px;
			background-color: #1890FF;
		}

		.selectCity {
			position: relative;

			/deep/.uni-easyinput__content-input {
				padding-left: 40rpx !important;
				display: flex;
				align-items: center;

			}

			.dropDownImage {
				position: absolute;
				top: 28rpx;

				right: 18rpx
			}

		}

		.selectProject {

			display: flex;
			align-items: center;


			.dropDownicons {
				margin-left: 80rpx;
				position: absolute;
				right: 0;
				padding-right: 20rpx;


			}

		}

		.searchButton {
			display: flex;
			align-items: center;

			.searchText {
				width: 70px;
				text-align: center;
				background-color: #6568F6;
				color: #FFFFFF;
				padding: 10px;
			}
		}
	}
</style>